<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.agentName" style="width: 200px;margin-right:15px;" class="filter-item" placeholder="请输入管理员名称" >
      </el-input>
      <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.agentPhone" style="width: 200px;margin-right:15px;" class="filter-item" placeholder="请输入管理员手机" >
      </el-input>
      <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.area" style="width: 200px;margin-right:15px;" class="filter-item" placeholder="请输入管理员区域" >
      </el-input>
      <el-select v-model="listQuery.roleId" placeholder="请选择管理员类型" clearable class="filter-item" style="width: 250px;">
        <el-option v-for="item in wxRoles" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" v-waves type="primary" icon="el-icon-circle-plus-outline" @click="dialog.add=true,roleIds=''">添加</el-button>
    </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column  label="序号" prop='index' />
      <el-table-column  label="管理员手机号" prop='agentPhone' />
      <el-table-column  label="管理员姓名" prop='agentName' />
      <el-table-column  label="管理员类型" prop="roleName"></el-table-column>
      <el-table-column  label="管理员区域" prop='address' />
      <el-table-column  label="佣金比例" prop='commissionRatio' />
      <el-table-column  label="管理员状态">
        <template slot-scope="scope">
           <div>{{scope.row.isFlag == 2 ? '禁用中':'启用中'}}</div>
        </template>
      </el-table-column>
      <el-table-column  label="操作"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  size="mini" type='primary' v-if="scope.row.isFlag == 2" @click="changeStatus(scope.row.agentId,1)">启用
          </el-button>
          <el-button  size="mini" type="danger" v-else @click="changeStatus(scope.row.agentId,2)">禁用
          </el-button>   
          <el-button  size="mini" type='primary' @click="editor(scope.row)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <!-- 添加弹框 -->
    <el-dialog title="新增管理员" :visible.sync="dialog.add">
      <el-form :model="bindQuery" :rules='bindRules' ref="bindForm" label-position="right" label-width="120px"> 
        <el-form-item label="管理员手机号" prop="agentPhone">
         <el-input  clearable v-model="bindQuery.agentPhone" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="账户密码" prop='agentPassWord'>
          <el-input  clearable v-model="bindQuery.agentPassWord" placeholder="请输入账号密码"></el-input>
        </el-form-item >
        <el-form-item label="管理员名称" prop='agentName'>
          <el-input  clearable v-model="bindQuery.agentName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="管理员类型" prop='roleId'>
          <el-select v-model="bindQuery.roleId" @change="changes" placeholder="请选择类型">
            <el-option :label="item.roleName" v-for="(item,index) in wxRole" :key="index" :value="item.roleLevel"></el-option>
          </el-select>
        </el-form-item>
        <!-- 提示：（选择省管理员时显示这个） -->
        <el-form-item label="省" prop="agentProvince" v-if="roleIds ==1 || roleIds == 2 || roleIds == 3">
          <el-select clearable style="width: 100%"  @change="getCities"  v-model="bindQuery.agentProvince" placeholder="省" class="filter-item"  >
            <el-option v-for="p in provices" :label='p.NAME' :value='p.AREA_ID' :key='p.AREA_ID'/>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="agentCity" v-if="roleIds == 3 || roleIds == 2">
          <el-select clearable style="width: 100%" @change="getAreas" v-model="bindQuery.agentCity" placeholder="市" class="filter-item"  >
            <el-option v-for="c in cities" :label='c.NAME' :value='c.AREA_ID' :key='c.AREA_ID' />
          </el-select>
        </el-form-item>
        <el-form-item label="佣金比例" prop='commissionRatio'>
          <el-input  clearable v-model="bindQuery.commissionRatio" type="number" min="1" max="99" placeholder="请输入佣金比例"></el-input>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">添加</el-button>
      </div>
    </el-dialog>
    <!-- 编辑管理员 -->
    <el-dialog title="编辑管理员" :visible.sync="dialog1.add">
      <el-form :model="bindQuery1" :rules='bindRules' ref="bindForm1" label-position="right" label-width="120px"> 
        <el-form-item label="管理员手机号" prop="agentPhone">
         <el-input  clearable v-model="bindQuery1.agentPhone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="管理员名称" prop='agentName'>
          <el-input  clearable v-model="bindQuery1.agentName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="管理员类型" prop='roleId'>
          <el-select v-model="bindQuery1.roleId" @change="changes" placeholder="请选择类型"  disabled >
            <el-option :label="item.roleName" v-for="(item,index) in wxRole" :key="index" :value="item.roleLevel"></el-option>
          </el-select>
        </el-form-item>
        <!-- 提示：（选择省管理员时显示这个） -->
        <el-form-item label="省" prop="agentProvince" v-if="roleIds != 0">
          <el-select clearable style="width: 100%"  @change="getCities"  v-model="bindQuery1.agentProvince" placeholder="省" class="filter-item" disabled >
            <el-option v-for="p in provices" :label='p.NAME' :value='p.AREA_ID' :key='p.AREA_ID'/>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="agentCity" v-if="roleIds == 3 || roleIds == 2">
          <el-select clearable style="width: 100%" @change="getAreas" v-model="bindQuery1.agentCity" placeholder="市" class="filter-item" disabled >
            <el-option v-for="c in cities" :label='c.NAME' :value='c.AREA_ID' :key='c.AREA_ID' />
          </el-select>
        </el-form-item>
        <el-form-item label="佣金比例" prop='commissionRatio'>
          <el-input  clearable v-model="bindQuery1.commissionRatio"  type="number" min="1" max="99" placeholder="请输入佣金比例"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog1.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="adds">添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getList, updAgentIsFlag, getWxRoleList, addAgent, updAgent, getAllWxRoleList } from '@/api/administrator'
import { validatePhone } from '@/utils/validate'
import {getAddress, getId, getAddressByAreaId} from '@/utils/getAddress'
import pcq from '@/components/index'
export default {
  name: 'user_list',
  data() {
     var validatePass = (rule, value, callback) => {
        if (!validatePhone(value)) {
          return callback(new Error('请填写正确的手机号码'));
        } else {
          callback();
        }
      };
    return {
      total: 0,
      show: false,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        agentName: '',
        agentPhone:'',
        area: ''
      },
      list: null,
      loading: {
        list: false,
        add: false
      },
      dialog:{
        add:false
      },
      dialog1:{
        add:false
      },
      bindQuery:{
        agentPassWord:'',
        agentName:'',
        agentPhone:'',
        roleId: '',
        agentProvince: '',
        agentCity: ''
      },
      bindQuery1: {
        agentId: '',
        agentName: '',
        agentPhone: '',
        roleId: '',
        agentProvince: '',
        agentCity: ''
      },
      bindRules:{
        agentPassWord: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        agentName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        agentPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ],
        agentProvince: [
          { required: true, message: '请选择省', trigger: 'blur' }
        ],
        agentCity:  [
          { required: true, message: '请选择市', trigger: 'blur' }
        ],
        commissionRatio:  [
          { required: true, message: '请输入佣金比例', trigger: 'blur' }
        ],
      },
      wxRole: [],
      wxRoles: [],
      roleIds: '',
      arr: [],
      provices: [],
      cities: [],
      areas: [],
    }
  },
  components:{
      pcq
  },
  methods: {
    //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId (fid) {
      return getAddressByAreaId(fid)
    },
    // 获取对应市
    getCities (fid) {
      // this.bindQuery.agentProvince = ''
      this.bindQuery.agentCity = ''
      this.areas = []
      this.cities = getAddressByAreaId(fid)     
    },
      // 获取对应的地区
    getAreas (fid) {
      // this.bindQuery.hospitalArea = ''
      this.areas = getAddressByAreaId(fid)
    },
    //选择角色
    changes(val) {
      this.roleIds = val
      this.arr = []
      this.bindQuery.agentProvince = ''
      this.bindQuery.agentCity = ''
      if(val == 1) {
        this.bindQuery1.agentProvince = ''
        this.bindQuery1.agentCity = ''
      }
    },
    //获取管理员列表
    async getLists() {
      this.loading.list = true
      try {
        const { data } = await getList(this.listQuery)
        console.log(data);
        this.list = data.agentList.map((item, index) => ({index: index + 1, ...item}))
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false     
    },
    //获取管理员角色类型
    async getWxRoleLists() {
      try{
        const { data } = await getWxRoleList()
        this.wxRole = data.wxRoleList
      }catch (error){

      }
      
    },
    async getAllWxRoleLists() {
      try{
        const { data } = await getAllWxRoleList()
        this.wxRoles = data.wxRoleList
      }catch (error){

      }
      
    },
    //禁用启用
    changeStatus(agentId,status) {
      let type = status == 1 ?"启用":"禁用";
      this.$confirm(`是否${type}?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
      }).then(async () => {
          const {data }= await updAgentIsFlag({
            agentId:agentId,
            isFlag:status
          })
          this.$message({
              type: 'success',
              message: `${type}成功!`
          });
            this.getLists()
          }).catch(() => {
                
          });
    }, 
    //新增
    add() {
      this.$refs['bindForm'].validate(async (valid) => {
        if (valid) {
          if(Number(this.bindQuery.commissionRatio) > 99 || Number(this.bindQuery.commissionRatio) < 1) {
            this.$message({
              type:'error',
              message: '佣金比例在1~99范围内'
            })
            return
          }
          this.loading.add = true
          this.bindQuery.roleId = this.wxRole.filter(item => item.roleLevel == this.roleIds)[0].roleId
          let a = {...this.bindQuery,agentProvince: getAddress(this.bindQuery.agentProvince),agentCity: getAddress(this.bindQuery.agentCity)}
          try{ 
            const { data } = await addAgent(a)
            this.$message({
              type: 'success',
              message: `新增成功!`
            });
            this.dialog.add = false
            this.loading.add = false
            this.$refs['bindForm'].resetFields()
            this.getLists()
          } catch (error) {
              this.dialog.add = false
              this.loading.add = false
              this.$refs['bindForm'].resetFields() 
            }
        }
      })
    },
     //编辑
    adds() {
      this.$refs['bindForm1'].validate(async (valid) => {
        if (valid) {
          if(Number(this.bindQuery.commissionRatio) > 99 || Number(this.bindQuery.commissionRatio) < 1) {
            this.$message({
              type:'error',
              message: '佣金比例在1~99范围内'
            })
            return
          }
          this.loading.add = true
          this.bindQuery1.roleId = this.wxRole.filter(item => item.roleLevel == this.roleIds)[0].roleId
          let a = {...this.bindQuery1,agentProvince: getAddress(this.bindQuery1.agentProvince),agentCity: getAddress(this.bindQuery1.agentCity)}
          try{ 
            const { data } = await updAgent(a)
            this.$message({
              type: 'success',
              message: `编辑成功!`
            });
            this.dialog1.add = false
            this.$refs['bindForm1'].resetFields()
            this.getLists()
          } catch (error) {
                    
            }
        }
      })
    },
    //编辑渲染数据
    editor(item) {
      this.bindQuery1 = {
        agentId: '',
        agentName: '',
        agentPhone: '',
        roleId: '',
        agentProvince: '',
        agentCity: ''
      }
      console.log(item);
      this.arr = []
      this.dialog1.add = true
      this.bindQuery1.roleId = item.roleName
      this.bindQuery1.agentId = item.agentId
      this.bindQuery1.agentName = item.agentName
      this.bindQuery1.agentPhone = item.agentPhone
      this.bindQuery1.agentProvince = item.agentProvince
      this.bindQuery1.agentCity = item.agentCity
      let roleIdss = item.roleId
      this.bindQuery1.commissionRatio = item.commissionRatio
      this.roleIds = this.wxRole.filter(item => item.roleId == roleIdss)[0].roleLevel
      if(this.roleIds == 1) {
        let proviceId = getId(this.bindQuery1.agentProvince,this.bindQuery1.agentCity)
        this.arr = proviceId.split(' ')
        this.bindQuery1.agentProvince = this.arr[0]
        this.bindQuery1.agentCity = this.arr[1]
      }
    },
    //查找
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getLists()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getLists()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getLists()
    },
  },
  created() {
    this.getLists()
    this.getWxRoleLists()
    this.getAllWxRoleLists()
    this.provices = getAddressByAreaId(0)
  },
}
</script>
